package top.littlejiang.onlinexam.common.utils;

import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;

/**
 * @author chen
 * @Description
 * @since 2021/1/2 15:09
 */
public class PasswordUtils {
    public static int DEFAULT_LENGTH = 32;

    /**
     * 计算加密后的密码
     * @param userSalty
     * @param password
     * @return
     */
    public static String md5SaltyAndPwd(String userSalty, String password){
        return md5Hex(userSalty + password);
    }

    /**
     * 获取十六进制字符串形式的MD5摘要
     */
    public static String md5Hex(String src) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bs = md5.digest(src.getBytes());
            return new String(new Hex().encode(bs));
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 根据设置盐值长度 生成一个随机盐值
     * @param numSize
     * @return
     */
    public static String getRandomValue(int numSize) {
        String str = "";
        for (int i = 0; i < numSize; i++) {
            char temp = 0;
            int key = (int) (Math.random() * 2);
            switch (key) {
                case 0:
                    //产生随机数字
                    temp = (char) (Math.random() * 10 + 48);
                    break;
                case 1:
                    //产生a-f
                    temp = (char) (Math.random() * 6 + 'a');
                    break;
                default:
                    break;
            }
            str = str + temp;
        }
        return str;
    }

//    public static void main(String[] args) {
//        System.out.println(md5SaltyAndPwd("20a4b62dec6e4e5b5b7bf99d0cad6588", "1"));
//    }
}

